package com.hk.Mgr.web.controller.order;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.OrderInfoReq;
import com.hk.app.utils.ExcelService;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.*;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.OrganizationFiled;
import com.hk.commons.entity.UserChannel;
import com.hk.commons.entity.order.OrderContract;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.order.OrderRouteInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.view.OrderView;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.OrderExcelRes;
import com.hk.commons.vo.OrderStrMsg;
import com.hk.service.IFundInfo_Yimi;
import com.hk.service.IOrganization;
import com.hk.service.IOrganization_New;
import com.hk.service.kyc.ILogUtil;
import com.hk.service.order.*;
import com.hk.service.order.impl.OrderHandleContent;
import com.hk.service.product.ICompany;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ICacheService;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;
import com.hk.service.view.IOrderView;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/order")
public class OrderInfoCtrl extends BaseCtrl {

	@Value("${qingniu.pdf}")
	private String QN_PDF;

	@Value("${activity.baseUrl}")
	private String activitBaseUrl;

	@Autowired
	private IReservation reservationService;

	@Autowired
	private OrderHandleContent orderContent;

	@Autowired
	private ISysUser userService;

	@Autowired
	private ICompany companyService;


	@Autowired
	private IOrderContract orderContractService;


	@Autowired
	private IContract contractService;

	@Autowired
	private IOrganization orgService;

	@Autowired
	private IOrganization_New orgNewService;

	@Autowired
	private IProductInfo productService;

	@Autowired
	private IFundInfo_Yimi fundInfoService;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IOrderRouteInfo orderRouteService;

	@Autowired
	private ISysUserRoles roleService;

	@Autowired
	private ILogUtil logService;

	@Autowired
	private IOrderView orderViewService;

	private Logger logger = LoggerFactory.getLogger(OrderInfoCtrl.class);

	@Autowired
	public YingmiApiUtils utils;

    @Autowired
    private IParameter parmService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private ICacheService cacheService;


	/**
	 * 获得所有订单信息
	 *
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public ResponseBase<List<OrderExcelRes>> listOrder(
			@RequestBody OrderInfoReq req) {
		logger.info("=======打款报备list===========>" + req.getChannel() + "\t" + req.getOrgId());
		List<OrderExcelRes> orderExcellist = new ArrayList<OrderExcelRes>();
		ResponseBase<List<OrderExcelRes>> resp = new ResponseBase<>();

		if (req.getUserId() == null) {
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("请登录后再尝试！");
			return resp;
		}

		String id = req.getId();
		String userId = req.getUserId().toString();
		String userName = req.getUserName();
		String beginDateStr = req.getBeginDate();
		String endDateStr = req.getEndDate();
		String financialName = req.getFinancialName();

		Integer curPage = req.getCurPage();
		Integer pageSize = req.getPageSize();

		Integer payStatus = req.getPayStatus();
		Integer company = req.getCompany();
		Long productId = req.getProductId();

		String contractTitle = req.getContractTitle();

		//渠道
		Integer channel = req.getChannel();
		//分公司
		String orgId = req.getOrgId();

		logger.info("order/list info:" + " userName =" + req.getUserName()
				+ " productId =" + req.getProductId() + " id = " + req.getId()
				+ " payStatus = " + req.getPayStatus() + " beginDate ="
				+ req.getBeginDate() + " endDate = " + req.getEndDate()
				+ " company=" + company + " financialName = " + financialName + "channel=" + channel + "orgId=" + orgId);

		logger.info("get orderList userId={}", userId);

		if (pageSize < 1000) {
			orderExcellist = getAllOrderMsg(id, userId, userName,
					financialName, productId, beginDateStr, endDateStr,
					payStatus, curPage, pageSize, company, contractTitle, channel, orgId);

			resp.setResult(orderExcellist);
			resp.setSize(orderExcellist.size());
		} else {

			orderExcellist.add(new OrderExcelRes());
			Integer size = getTotalSize(id, userId, userName, financialName,
					productId, payStatus, beginDateStr, endDateStr, company, contractTitle, channel, orgId);
			resp.setSize(size);
			resp.setResult(orderExcellist);
		}

		resp.setResultCode(StatusCode.SUCCESS.key());
		return resp;
	}

    /**
     * 获得所有订单信息
     *
     * @return
     * @author jeff
     */
    @RequestMapping(value = "/excel")
    @ResponseBody
    public void excelExport(HttpServletRequest request,
                            HttpServletResponse response, @RequestParam String id,
                            @RequestParam String userId, @RequestParam String userName,
                            @RequestParam String financialName, @RequestParam Long productId,
                            @RequestParam Integer payStatus, @RequestParam String beginDateStr,
                            @RequestParam String endDateStr, @RequestParam Integer company, @RequestParam String contractTitle,
							@RequestParam Integer channel, @RequestParam String orgId) {
        userId = userId.split(",")[0];
        logger.info("order/list 传入的参数为" + " id = " + id + " userName ="
                + userName + " productId =" + productId + " beginDate ="
                + beginDateStr + " endDate = " + endDateStr + " userId ="
                + userId + "channel=" + channel +"orgId=" +orgId);
        List<OrderExcelRes> orderExcellist = getAllOrderMsg(id, userId,
                userName, financialName, productId, beginDateStr, endDateStr,
                payStatus, 0, 65535, company, contractTitle, channel, orgId);// 银行卡号，银行身份证，银行信息

        LinkedHashMap<String, String> struct = new LinkedHashMap<>();
        struct.put("col01id", "订单号");
        struct.put("col02amount", "付款订单金额");
        struct.put("col03niggerAmount", "折标金额");
        struct.put("col04status", "订单状态");
        struct.put("col05orderType", "订单类型");

        struct.put("col10productName", "产品名称");
        struct.put("col11productParName", "产品父标名称");
        struct.put("col13productCode", "产品code");
        struct.put("col14productCompanyName", "发行公司名称");
        struct.put("col15productTerm", "产品投资期限");
        struct.put("col16clearDate","预计清算时间");
        struct.put("col17directional","是否定向");

        struct.put("col21userName", "客户姓名");
        struct.put("col22userPhoneNum", "客户手机号");
        struct.put("col23insideName", "理财师姓名");
        struct.put("col24insidePhoneNum", "理财师手机号");
        struct.put("col25insideDepName", "理财师所属部门");
        struct.put("col26channel", "订单渠道");
        struct.put("col27channelName", "渠道名称");
        struct.put("col28orgName", "订单所属部门");
        struct.put("col29closeAccount","用户销户状态");

        struct.put("col31contractTitle", "电子合同标题");
        struct.put("col32contractUrlPDf", "电子合同pdf链接");
        struct.put("col32contractUrlHTML", "电子合同HTML链接");

		struct.put("col36contractTitle1", "电子合同标题1");
		struct.put("col36contractUrlPDF1", "电子合同pdf链接1");
		struct.put("col36contractUrlHTML1", "电子合同HTML链接1");

		struct.put("col36contractTitle2", "电子合同标题2");
		struct.put("col36contractUrlPDF2", "电子合同pdf链接2");
		struct.put("col36contractUrlHTML2", "电子合同HTML链接2");

		struct.put("col36contractTitle3", "电子合同标题3");
		struct.put("col36contractUrlPDF3", "电子合同pdf链接3");
		struct.put("col36contractUrlHTML3", "电子合同HTML链接3");

		struct.put("col36contractTitle4", "电子合同标题4");
		struct.put("col36contractUrlPDF4", "电子合同pdf链接4");
		struct.put("col36contractUrlHTML4", "电子合同HTML链接4");

		struct.put("col36contractTitle5", "电子合同标题5");
		struct.put("col36contractUrlPDF5", "电子合同pdf链接5");
		struct.put("col36contractUrlHTML5", "电子合同HTML链接5");

        struct.put("col33confirmationTitle", "投资确认函标题");
        struct.put("col34confirmationPdf", "投资确认函pdf链接");
        struct.put("col35confirmationHtml", "投资确认函HTML链接");

        struct.put("col410proRate", "产品收益率");
        struct.put("col412prodDividend", "产品收益");
        struct.put("col420prodAddRate", "产品额外加息收益率");
        struct.put("col421addRateDividend", "产品额外加息收益");
        struct.put("col430userCardId", "加息券id");
        struct.put("col431userCardRate", "加息券收益率");
        struct.put("col432userCardDividend", "加息券收益");
        struct.put("col433extraTerm", "加息券加息天数");
		struct.put("col4301userCardId", "贴息券id");
		struct.put("col4311userCardRate", "贴息券收益率");
		struct.put("col4321userCardDividend", "贴息券收益");
		struct.put("col435userCardFaceValue","贴息券面值");

        struct.put("col480extRate", "额外收益率");
        struct.put("col481extraDividend", "额外收益");
        struct.put("col490totalRate", "总收益率");
        struct.put("col491dividend", "总收益");

        struct.put("col51cts", "订单确认时间");
        struct.put("col52dividendDate", "回款日");
        struct.put("col53beginProfitDate", "起息时间");

		struct.put("riskLevel", "测评结果");
		struct.put("kycUrl", "测评链接");

        Boolean isOpear = roleService.isOperationalManager(Long.valueOf(userId));
        if (isOpear) {
            struct.put("col71identity", "客户身份证号码");
            struct.put("col72bankName", "交易所属银行");
            struct.put("col73paymentNo", "订单扣款银行卡");
            struct.put("col74subBankName", "开户行信息");
        }

        ExcelService excelService = new ExcelService(orderExcellist, struct);

        String title = "订单列表";
        excelService.exportToStream(response, title);
    }

    /**
     * 获取总的条目数
     *
     * @param id
     * @param userId
     * @param userName
     * @param financialName
     * @param productId
     * @param payStatus
     * @param beginDateStr
     * @param endDateStr
     * @param company
     * @param contractTitle
     * @return
     */
    private Integer getTotalSize(String id, String userId, String userName,
                                 String financialName, Long productId, Integer payStatus,
                                 String beginDateStr, String endDateStr, Integer company, String contractTitle, Integer channel, String orgId) {

        HqlFilter hqlFilter = getFilter(id, userId, userName, financialName,
                productId, beginDateStr, endDateStr, payStatus, company, contractTitle, channel, orgId);
        logger.info("获取总数目的筛选条件是: " + hqlFilter.getWhereHql());

        String md5 = MD5Crypter.md5Encrypt(hqlFilter.getWhereHql());
        logger.info("获取总数目的筛选条件MD5值是: " + md5);
        String redisKey = CacheConstants.ORDER_TOTAL_SIZE_PRE +md5;

        Integer result;

        if (RedisCilent.existsKey(redisKey)) {
            result = Integer.valueOf(RedisCilent.getString(redisKey));
            logger.info("Redis Key [{}]  hit cache ", redisKey);
        } else {
            synchronized (this) {
                result = Integer.valueOf(orderRouteService.countByFilter(hqlFilter).toString());
            }
            int expireSecond = cacheService.getExpireSecond();
            RedisCilent.setString(redisKey, result.toString(), expireSecond);
            logger.info("Redis Key [{}] cache : {} seconds", redisKey, expireSecond);
        }

        return result;
    }

    private HqlFilter getFilter(String id, String userId, String userName,
			String financialName, Long productId, String beginDateStr,
			String endDateStr, Integer payStatus, Integer company, String contractTitle, Integer channel, String orgId) {
		HqlFilter hqlFilter = new HqlFilter();

		logger.info("获取订单列表 传入的参数为" + " orderId = " + id + " userName ="
				+ userName + " productId =" + productId + " beginDate ="
				+ beginDateStr + " endDate = " + endDateStr + " company="
				+ company);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Date beginDate;
		Date endDate;

		hqlFilter.addSql(" where 1=1 ");


		try {
			// 增添日期筛选条件
			if (StringUtils.isNotEmpty(beginDateStr)) {
				beginDate = format.parse(beginDateStr);
				hqlFilter.addSql(" and cts > " + beginDate.getTime());
			}

			if (StringUtils.isNotEmpty(endDateStr)) {
				endDate = format.parse(endDateStr);

				Long endTimeLong = endDate.getTime() + 60 * 60 * 24 * 1000;

				hqlFilter.addSql(" and cts < " + endTimeLong);
			}
			if (company != 10) {
				hqlFilter.addEQFilter("companyId", company);
			}

			//渠道、分公司
			if (orderService.getCustomFieldForOrderInfo(channel, orgId, hqlFilter)) return hqlFilter;

		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			logger.info("order/list 日期格式转换错误");
			e1.printStackTrace();
		}

		if (StringHelper.isNotEmpty(id)) {
			hqlFilter.addEQFilter("orderId", Long.valueOf(id.trim()));
		} else {

			SysUser user = userService.findById(Long.valueOf(userId));

			Boolean isOpear = roleService.isOperationalManager(user.getId());
			// 如果不是运营部的人员，则添加筛选条件
			if (!isOpear) {
				// 增加组织架构的筛选
				if (user.getOrgId() != null) {
					Organization org = orgService.findById(user.getOrgId());
					// 如果用户的组织架构不为空，且为部门负责人

					//如果用户是部门负责人
					if(roleService.isDepLeader(Long.valueOf(userId)) ){
						logger.info("user is leader, userId ={}", userId);


						String appendSql = " channel = -1 ";
						List<Integer > channelIdList  = orgNewService.getDepLeaderChannelStrList(Long.valueOf(userId));

						for(Integer channelId : channelIdList){
							appendSql += " or channel = " + channelId ;
						}

						hqlFilter.addSql(" and orderId in (select id from OrderInfo where " + appendSql + ")");


						//logger.info(" hqlFilter = " + hqlFilter.getWhereAndOrderHql());
					}else if (org != null && org.getIsHeader() == 1 && roleService.isTeamLeader(Long.valueOf(userId))) {
						//如果是某个团队的负责人
						String code = orgService.getOrgLeaderCodeByOrgId(org
								.getId());
						hqlFilter
								.addSql(" and orderId in (select id from OrderInfo where orgId in (select id from  Organization where code like '"
										+ code + "%'))");
					} else {
						hqlFilter.addSql(" and ( userId = " + userId
								+ " or financialPlannerId = " + userId + " )");
					}
				}
			}

			if(StringHelper.isNotEmpty(contractTitle)){
				hqlFilter
						.addSql(" and orderId in (select id from OrderInfo where contractTitle  like '%" +
								"" + contractTitle + "%')");
			}

			boolean userNotEmpty = StringUtils.isNotEmpty(userName);
			if (userNotEmpty) {
				String findNameForIds = "select id from SysUser where Name like '%"+userName+"%' OR RealName like  '%"+userName+"%'";
				String userIds = getUserIds(findNameForIds);

				if(userIds.length() != 0) {
					hqlFilter
							.addSql(" and userId in ("+ userIds +") ");
				}
			}

			boolean financialNameNotEmpty = StringUtils.isNotEmpty(financialName);
			if (financialNameNotEmpty) {
				String findNameForIds = "select id from SysUser where Name like '%"+financialName+"%' OR RealName like  '%"+financialName+"%'";
				String userIds = getUserIds(findNameForIds);
				if(userIds.length() != 0) {
					hqlFilter
							.addSql(" and financialPlannerId in ("+userIds+") ");
				}

			}

			if (productId != null) {
				hqlFilter.addEQFilter("productId", productId);
			}

			if (payStatus != null) {
				hqlFilter
						.addSql(" and orderId in (select id from  OrderInfo where payStatus = "
								+ payStatus + ")");
			} else {
				hqlFilter
						.addSql(" and orderId in (select id from  OrderInfo where payStatus in (2,4,5) )");
			}

		}

		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");
//		logger.info("筛选条件是" + hqlFilter.getWhereHql());
		logger.info("获取分页的筛选条件是" + hqlFilter.getWhereHql());
		return hqlFilter;
	}


	/**
	 * 通过手机 查找用户id
	 * @param findNameForIds
	 * @return
	 */
	private String getUserIds(String findNameForIds) {
		List<Long> idsList = jdbcTemplate.queryForList(findNameForIds, Long.class);
		String userIds = "";
		for(Long idsLists : idsList){
            userIds += idsLists + ",";
        }
		userIds =  (userIds.substring(0,userIds.length()-1)).toString();
		return userIds;
	}


	/**
	 *
	 * @param id
	 *            订单id
	 * @param userName
	 *            客户姓名/手机号
	 * @param productId
	 *            产品id
	 * @param beginDateStr
	 *            购买开始时间，购买结束时间
	 * @param endDateStr
	 *            查询结束时间
	 *
	 * @return orderExcellist
	 */
    public List<OrderExcelRes> getAllOrderMsg(String id, String userId,
                                              String userName, String financialName, Long productId,
                                              String beginDateStr, String endDateStr, Integer payStatus,
                                              Integer curPage, Integer pageSize, Integer company, String contractTitle,Integer channel, String orgId) {


		logger.info("getAllOrderMsg userId ={}", userId);

        // 获取筛选条件
        HqlFilter hqlFilter = getFilter(id, userId, userName, financialName,
                productId, beginDateStr, endDateStr, payStatus, company, contractTitle, channel, orgId);

        List<OrderRouteInfo> orderRouteList = orderRouteService.findByFilter(
                hqlFilter, curPage, pageSize);

        // 封装并获取订单信息
        Long userIdAsLong = Long.valueOf(userId);
        Boolean isOpear = roleService.isOperationalManager(userIdAsLong);
        Boolean isChannelLeader = roleService.isDepLeader(userIdAsLong);
        Boolean isTeamLeader = roleService.isTeamLeader(userIdAsLong);
        List<OrderExcelRes> orderExcelList;

        logger.info("Start streaming for {} ,from {} to {}",userId,beginDateStr,endDateStr);
        orderExcelList = orderRouteList
                .parallelStream()
                .map(orderRoute -> orderContent.getOrderInfo(orderRoute.getOrderId(), orderRoute.getUserId(), orderRoute.getCompanyId()))
                .filter(msg -> msg != null && StringUtils.isNotBlank(msg.getId()))
                .map(msg -> orderService.getOrderExcelRes(msg, isOpear, isChannelLeader, isTeamLeader))
                .collect(Collectors.toList());
        logger.info("End streaming for {} ,from {} to {}",userId,beginDateStr,endDateStr);

        return orderExcelList;
    }


    /**
     * 生成电子合同
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createContract", method = RequestMethod.GET)
    public ResponseBase createContract(@RequestParam Long orderId) {
        ResponseBase<String> result = new ResponseBase<>();

        OrderInfo orderInfo = orderService.findById(orderId);
        if (orderInfo == null) {
            genErrorResponse(result, "订单" + orderId + "不存在");
            return result;
        }

        if (StringUtils.isNotBlank(orderInfo.getContractUrl())) {
            genErrorResponse(result, "电子合同" + orderId + "早已生成!");
            return result;
        }

        boolean createResult = contractService.create(orderId);

        if (!createResult) {
            genErrorResponse(result, "电子合同" + orderId + "生成失败,如需要请联系运营人员");
            return result;
        }

        result.setResultCode(StatusCode.SUCCESS.key());
        result.setMsg("电子合同" + orderId + "生成完毕!");
        return result;
    }

	/**
	 * 生成电子合同
	 *
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createKYCDoc", method = RequestMethod.GET)
	public ResponseBase  createKYCDoc(@RequestParam Long orderId) {


		ResponseBase<String> result = new ResponseBase<>();
		orderService.createOrderKyc(orderId);
		result.setResultCode(StatusCode.SUCCESS.key());
		result.setMsg("分线测评生成完毕! 请重新刷新页面");
		return result;
	}


    /**
     * 生成投资确认函
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createTZQRH", method = RequestMethod.GET)
    public ResponseBase createTZQRH(@RequestParam Long orderId) {
        ResponseBase<String> result = new ResponseBase<>();

        OrderInfo orderInfo = orderService.findById(orderId);
        if (orderInfo == null) {
            genErrorResponse(result, "订单" + orderId + "不存在");
            return result;
        }

        if (!orderInfo.getConfirmStatus().equals(ConstantOrderStatus.CONFIRM_STATUS__TRUE)
                && !orderInfo.getConfirmStatus().equals(ConstantOrderStatus.CONFIRM_STATUS__PAYBACK)) {
            genErrorResponse(result, "订单" + orderId + "未起标");
            return result;
        }

        if (StringUtils.isNotBlank(orderInfo.getConfirmationPdf())) {
            genErrorResponse(result, "投资确认函" + orderId + "早已生成! 请重新刷新页面");
            return result;
        }

        boolean createResult = contractService.creatTZQRHPDF(orderId);

        if (!createResult) {
            genErrorResponse(result, "投资确认函" + orderId + "生成失败,如需要请联系运营人员");
            return result;
        }

        result.setResultCode(StatusCode.SUCCESS.key());
        result.setMsg("投资确认函" + orderId + "生成完毕! 请重新刷新页面");
        return result;
    }

    private void genErrorResponse(ResponseBase<String> result, String msg) {
        result.setResultCode(StatusCode.ERROR.key());
        result.setMsg(msg);
    }

    /**
	 * 修改订单的推荐码和渠道
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateCode", method = RequestMethod.POST)
	public ResponseBase<OrderInfo> updateCode(@RequestBody OrderInfoReq req) {


		ResponseBase<OrderInfo> resp = new ResponseBase<OrderInfo>();

		try {

			if(req == null || req.getActUserId() == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录后再尝试 !");
				return resp;
			}

			if (StringHelper.isEmpty(req.getId()) || StringHelper.isEmpty(req.getRecommendCode())) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对,部分参数为空 !");
				return resp;
			}

			logger.info("update order channel and code  操作者的id ={}, orderId={}, recommandCode={}", req.getActUserId(), req.getId(), req.getRecommendCode());


			String  recommendCode = req.getRecommendCode();
			SysUser finUser = userService.getByPhoneNum(recommendCode);

			if(finUser == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("理财师不存在，此次修改失败 !");
				return resp;
			}

			if(finUser.getIsInside() != 1){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("该推荐码所属客户不是理财师，此次修改失败 !");
				return resp;
			}

			Long orderId = Long.valueOf(req.getId());


			CheckInfo checkInfo = orderService.updOrderFinUserId(finUser, orderId, req.getActUserId());

			if(checkInfo.getResult()) {

				//修改成功时，如果有使用到优惠券，把优惠券的记录也更新
				OrderView orderView = orderViewService.findById(orderId);
				OrderInfo orderInfo = orderService.findById(orderId);
				if(orderView !=null && orderInfo !=null && orderInfo.getUserCardId()!=null){
					String orderBelongOrg = URLEncoder.encode(orderView.getOrderOrgName(),"UTF-8");
					String url = activitBaseUrl+"/api/couponWallet/update/"+orderInfo.getUserCardId()+"/"+orderBelongOrg;
					try {
						HttpUtils.invokePost(url,null,30);
					}catch (Exception e){
						logger.error("更新该订单使用的卡券所属部门失败！{}",e);
					}
				}

				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("修改成功");
			}else {
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg(checkInfo.getResultMsg());
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}


	/**
	 * 获取订单合同
	 * @return
	 */
	@RequestMapping(value = "/contracts", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase<List<OrderContract>> contracts(@RequestParam Long orderId) {

		ResponseBase<List<OrderContract>> resp = new ResponseBase<>();
		List<OrderContract> contractList = orderContractService.getOrderContractList(orderId);
		resp.setResult(contractList);
		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setMsg("成功!");
		return resp;
	}
	/**
	 * 修改订单的推荐码和渠道
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/mutiUpdateCode", method = RequestMethod.POST, consumes="application/json")
	@ResponseBody
	public ResponseBase<Boolean> mutiUpdateCode(@RequestBody OrderInfoReq req) {


		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();

		try {

			if(req == null || req.getActUserId() == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录后再尝试 !");
				return resp;
			}

			if (StringHelper.isEmpty(req.getIds()) || StringHelper.isEmpty(req.getRecommendCode())) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对,部分参数为空 !");
				return resp;
			}

			logger.info("update order channel and code  操作者的id ={}, orderId={}, recommandCode={}", req.getActUserId(), req.getId(), req.getRecommendCode());

			String  recommendCode = req.getRecommendCode();
			SysUser finUser = userService.getByPhoneNum(recommendCode);

			if(finUser == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("理财师不存在，此次修改失败 !");
				return resp;
			}

			if(finUser.getIsInside() != 1){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("该推荐码所属客户不是理财师，此次修改失败 !");
				return resp;
			}

			String[] arrayIds = req.getIds().split(",");

			List<String> orderIdList = Arrays.asList(arrayIds);

			List<CheckInfo> errResultList = orderIdList.parallelStream()
					.map(orderIdStr -> Long.valueOf((String)orderIdStr))
					.map(orderIdLong -> orderService.updOrderFinUserId(finUser, orderIdLong, req.getActUserId()) )
					.filter(checkInfo -> checkInfo.getResult() == false)
					.collect(Collectors.toList());

			if(errResultList == null || errResultList.size() == 0){
				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("修改成功");
			}else{
				resp.setResult(false);
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("部分修改失败");
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}

	private OrderExcelRes getOrderExcelRes(OrderInfo order, Long userId) {
		if (order == null) {
			return null;
		}

		OrderStrMsg orderMsg = orderContent.getOrderInfo(order.getId(),
				order.getUserId(), order.getCompanyId());

		if (orderMsg == null) {
			return null;
		}

		OrderExcelRes orderExcelRes = orderService.getOrderExcelRes(orderMsg, userId);

		if (orderExcelRes == null) {
			return null;
		}
		return orderExcelRes;
	}

	/**
	 * 通过channelId查找分公司
	 * @param channelId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getOrg", method = RequestMethod.GET)
	public ResponseBase<List<OrganizationFiled>> getOrgList(String channelId) {
		logger.info("==/getOrg==============获取分公司=================" + channelId);
		ResponseBase resp = new ResponseBase();
		List<OrganizationFiled> list = orderService.getOrgList(channelId);

		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setResult(list);
		return resp;
	}

	/**
	 *渠道过滤
	 * @param requestUserId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserList", method = RequestMethod.POST)
	public ResponseBase<List<UserChannel>> getUserList(@RequestBody String requestUserId) {
		logger.info("获取渠道===>" + requestUserId);
		ResponseBase<List<UserChannel>> resp = new ResponseBase<List<UserChannel>>();
		JSONObject jsStr = JSONObject.fromObject(requestUserId);
		String userId = jsStr.get("userId").toString();

		List<UserChannel> result = orderService.getUserList(userId);

		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setResult(result);
		return resp;
	}

}
